<template>
  <div class="post-loan-statistics">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>贷后统计分析</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport">导出报表</el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <el-form :model="filterForm" inline class="filter-form">
        <el-form-item label="统计周期">
          <el-select v-model="filterForm.period" placeholder="请选择统计周期" @change="handlePeriodChange">
            <el-option label="本月" value="month"></el-option>
            <el-option label="本季度" value="quarter"></el-option>
            <el-option label="本年度" value="year"></el-option>
            <el-option label="自定义" value="custom"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" v-if="filterForm.period === 'custom'">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="statistics-card">
            <div class="statistics-card-title">贷后检查</div>
            <div class="statistics-card-value">{{ statisticsData.inspectionCount }}</div>
            <div class="statistics-card-footer">
              <span>完成率: {{ statisticsData.inspectionCompletionRate }}%</span>
              <el-progress 
                :percentage="statisticsData.inspectionCompletionRate" 
                :color="statusColors.primary"
                :stroke-width="6"
              ></el-progress>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="statistics-card">
            <div class="statistics-card-title">贷后跟踪</div>
            <div class="statistics-card-value">{{ statisticsData.trackCount }}</div>
            <div class="statistics-card-footer">
              <span>完成率: {{ statisticsData.trackCompletionRate }}%</span>
              <el-progress 
                :percentage="statisticsData.trackCompletionRate" 
                :color="statusColors.success"
                :stroke-width="6"
              ></el-progress>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="statistics-card">
            <div class="statistics-card-title">贷后评估</div>
            <div class="statistics-card-value">{{ statisticsData.assessmentCount }}</div>
            <div class="statistics-card-footer">
              <span>完成率: {{ statisticsData.assessmentCompletionRate }}%</span>
              <el-progress 
                :percentage="statisticsData.assessmentCompletionRate" 
                :color="statusColors.warning"
                :stroke-width="6"
              ></el-progress>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="statistics-card">
            <div class="statistics-card-title">风险预警</div>
            <div class="statistics-card-value">{{ statisticsData.warningCount }}</div>
            <div class="statistics-card-footer">
              <span>处理率: {{ statisticsData.warningHandleRate }}%</span>
              <el-progress 
                :percentage="statisticsData.warningHandleRate" 
                :color="statusColors.danger"
                :stroke-width="6"
              ></el-progress>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 贷后检查统计 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">贷后检查统计</div>
            </template>
            <div class="chart-content" ref="inspectionChartRef"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">检查结果分布</div>
            </template>
            <div class="chart-content" ref="inspectionResultChartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 贷后跟踪和评估统计 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">跟踪风险等级分布</div>
            </template>
            <div class="chart-content" ref="trackRiskChartRef"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">评估等级分布</div>
            </template>
            <div class="chart-content" ref="assessmentRatingChartRef"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 预警统计和月度趋势 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">预警等级分布</div>
            </template>
            <div class="chart-content" ref="warningLevelChartRef"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">贷后工作月度趋势</div>
            </template>
            <div class="chart-content" ref="monthlyTrendChartRef"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts/core'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import { postloanStatisticsApi } from '@/api/postloan'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  BarChart,
  LineChart,
  PieChart,
  CanvasRenderer
])

// 筛选条件
const filterForm = reactive({
  period: 'month',
  dateRange: [
    new Date(new Date().setDate(1)).toISOString().split('T')[0],
    new Date().toISOString().split('T')[0]
  ]
})

// 统计数据
const statisticsData = reactive({
  inspectionCount: 0,
  inspectionCompletionRate: 0,
  trackCount: 0,
  trackCompletionRate: 0,
  assessmentCount: 0,
  assessmentCompletionRate: 0,
  warningCount: 0,
  warningHandleRate: 0
})

// 状态颜色
const statusColors = {
  primary: '#409EFF',
  success: '#67C23A',
  warning: '#E6A23C',
  danger: '#F56C6C'
}

// 图表引用
const inspectionChartRef = ref(null)
const inspectionResultChartRef = ref(null)
const trackRiskChartRef = ref(null)
const assessmentRatingChartRef = ref(null)
const warningLevelChartRef = ref(null)
const monthlyTrendChartRef = ref(null)

// 图表实例
let inspectionChart = null
let inspectionResultChart = null
let trackRiskChart = null
let assessmentRatingChart = null
let warningLevelChart = null
let monthlyTrendChart = null

// 周期变更处理
const handlePeriodChange = () => {
  if (filterForm.period !== 'custom') {
    // 设置为当前周期的开始和结束日期
    const now = new Date()
    let startDate = new Date()
    
    if (filterForm.period === 'month') {
      // 当月1号
      startDate = new Date(now.getFullYear(), now.getMonth(), 1)
    } else if (filterForm.period === 'quarter') {
      // 当季度第一个月1号
      const quarterStartMonth = Math.floor(now.getMonth() / 3) * 3
      startDate = new Date(now.getFullYear(), quarterStartMonth, 1)
    } else if (filterForm.period === 'year') {
      // 当年1月1号
      startDate = new Date(now.getFullYear(), 0, 1)
    }
    
    filterForm.dateRange = [
      startDate.toISOString().split('T')[0],
      now.toISOString().split('T')[0]
    ]
  }
}

// 重置筛选
const resetFilter = () => {
  filterForm.period = 'month'
  handlePeriodChange()
  fetchData()
}

// 获取数据
const fetchData = () => {
  fetchOverviewData()
  fetchInspectionData()
  fetchTrackData()
  fetchAssessmentData()
  fetchWarningData()
  fetchMonthlyTrendData()
}

// 获取总体统计数据
const fetchOverviewData = () => {
  const params = {
    startDate: filterForm.dateRange[0],
    endDate: filterForm.dateRange[1]
  }
  
  postloanStatisticsApi.getOverview(params).then(res => {
    const data = res.data
    statisticsData.inspectionCount = data.inspectionCount
    statisticsData.inspectionCompletionRate = data.inspectionCompletionRate
    statisticsData.trackCount = data.trackCount
    statisticsData.trackCompletionRate = data.trackCompletionRate
    statisticsData.assessmentCount = data.assessmentCount
    statisticsData.assessmentCompletionRate = data.assessmentCompletionRate
    statisticsData.warningCount = data.warningCount
    statisticsData.warningHandleRate = data.warningHandleRate
  }).catch(() => {
    ElMessage.error('获取总体统计数据失败')
  })
}

// 获取检查统计数据
const fetchInspectionData = () => {
  const params = {
    startDate: filterForm.dateRange[0],
    endDate: filterForm.dateRange[1]
  }
  
  postloanStatisticsApi.getInspectionStats(params).then(res => {
    const data = res.data
    updateInspectionChart(data)
    updateInspectionResultChart(data)
  }).catch(() => {
    ElMessage.error('获取检查统计数据失败')
  })
}

// 获取跟踪统计数据
const fetchTrackData = () => {
  const params = {
    startDate: filterForm.dateRange[0],
    endDate: filterForm.dateRange[1]
  }
  
  postloanStatisticsApi.getTrackStats(params).then(res => {
    const data = res.data
    updateTrackRiskChart(data)
  }).catch(() => {
    ElMessage.error('获取跟踪统计数据失败')
  })
}

// 获取评估统计数据
const fetchAssessmentData = () => {
  const params = {
    startDate: filterForm.dateRange[0],
    endDate: filterForm.dateRange[1]
  }
  
  postloanStatisticsApi.getAssessmentStats(params).then(res => {
    const data = res.data
    updateAssessmentRatingChart(data)
  }).catch(() => {
    ElMessage.error('获取评估统计数据失败')
  })
}

// 获取预警统计数据
const fetchWarningData = () => {
  const params = {
    startDate: filterForm.dateRange[0],
    endDate: filterForm.dateRange[1]
  }
  
  postloanStatisticsApi.getWarningStats(params).then(res => {
    const data = res.data
    updateWarningLevelChart(data)
  }).catch(() => {
    ElMessage.error('获取预警统计数据失败')
  })
}

// 获取月度趋势数据
const fetchMonthlyTrendData = () => {
  const params = {
    startDate: filterForm.dateRange[0],
    endDate: filterForm.dateRange[1]
  }
  
  postloanStatisticsApi.getMonthlyTrend(params).then(res => {
    const data = res.data
    updateMonthlyTrendChart(data)
  }).catch(() => {
    ElMessage.error('获取月度趋势数据失败')
  })
}

// 初始化图表
const initCharts = () => {
  // 贷后检查统计图表
  inspectionChart = echarts.init(inspectionChartRef.value)
  // 检查结果分布图表
  inspectionResultChart = echarts.init(inspectionResultChartRef.value)
  // 跟踪风险等级分布图表
  trackRiskChart = echarts.init(trackRiskChartRef.value)
  // 评估等级分布图表
  assessmentRatingChart = echarts.init(assessmentRatingChartRef.value)
  // 预警等级分布图表
  warningLevelChart = echarts.init(warningLevelChartRef.value)
  // 月度趋势图表
  monthlyTrendChart = echarts.init(monthlyTrendChartRef.value)
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    inspectionChart.resize()
    inspectionResultChart.resize()
    trackRiskChart.resize()
    assessmentRatingChart.resize()
    warningLevelChart.resize()
    monthlyTrendChart.resize()
  })
}

// 更新贷后检查统计图表
const updateInspectionChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['总计划数', '已完成', '进行中', '逾期']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.categories || []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '总计划数',
        type: 'bar',
        data: data.total || []
      },
      {
        name: '已完成',
        type: 'bar',
        data: data.completed || [],
        itemStyle: {
          color: statusColors.success
        }
      },
      {
        name: '进行中',
        type: 'bar',
        data: data.processing || [],
        itemStyle: {
          color: statusColors.warning
        }
      },
      {
        name: '逾期',
        type: 'bar',
        data: data.overdue || [],
        itemStyle: {
          color: statusColors.danger
        }
      }
    ]
  }
  
  inspectionChart.setOption(option)
}

// 更新检查结果分布图表
const updateInspectionResultChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: ['正常', '需关注', '风险']
    },
    series: [
      {
        name: '检查结果',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { 
            value: data.normalCount || 0, 
            name: '正常',
            itemStyle: { color: statusColors.success }
          },
          { 
            value: data.attentionCount || 0, 
            name: '需关注',
            itemStyle: { color: statusColors.warning }
          },
          { 
            value: data.riskCount || 0, 
            name: '风险',
            itemStyle: { color: statusColors.danger }
          }
        ]
      }
    ]
  }
  
  inspectionResultChart.setOption(option)
}

// 更新跟踪风险等级分布图表
const updateTrackRiskChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: ['正常', '关注', '次级', '可疑', '损失']
    },
    series: [
      {
        name: '风险等级',
        type: 'pie',
        radius: '55%',
        center: ['50%', '50%'],
        data: [
          { 
            value: data.normalCount || 0, 
            name: '正常',
            itemStyle: { color: statusColors.success }
          },
          { 
            value: data.attentionCount || 0, 
            name: '关注',
            itemStyle: { color: '#67C23A' }
          },
          { 
            value: data.secondaryCount || 0, 
            name: '次级',
            itemStyle: { color: statusColors.warning }
          },
          { 
            value: data.doubtfulCount || 0, 
            name: '可疑',
            itemStyle: { color: '#FF9900' }
          },
          { 
            value: data.lossCount || 0, 
            name: '损失',
            itemStyle: { color: statusColors.danger }
          }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  trackRiskChart.setOption(option)
}

// 更新评估等级分布图表
const updateAssessmentRatingChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: ['A-优秀', 'B-良好', 'C-一般', 'D-较差', 'E-极差']
    },
    series: [
      {
        name: '评估等级',
        type: 'pie',
        radius: ['30%', '50%'],
        center: ['50%', '50%'],
        roseType: 'area',
        data: [
          { 
            value: data.ratingACount || 0, 
            name: 'A-优秀',
            itemStyle: { color: '#67C23A' }
          },
          { 
            value: data.ratingBCount || 0, 
            name: 'B-良好',
            itemStyle: { color: '#409EFF' }
          },
          { 
            value: data.ratingCCount || 0, 
            name: 'C-一般',
            itemStyle: { color: '#E6A23C' }
          },
          { 
            value: data.ratingDCount || 0, 
            name: 'D-较差',
            itemStyle: { color: '#FF9900' }
          },
          { 
            value: data.ratingECount || 0, 
            name: 'E-极差',
            itemStyle: { color: '#F56C6C' }
          }
        ]
      }
    ]
  }
  
  assessmentRatingChart.setOption(option)
}

// 更新预警等级分布图表
const updateWarningLevelChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['一级预警', '二级预警', '三级预警']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['待处理', '处理中', '已完成', '已关闭']
    },
    series: [
      {
        name: '一级预警',
        type: 'bar',
        stack: 'total',
        label: {
          show: true
        },
        emphasis: {
          focus: 'series'
        },
        data: [
          data.level1Pending || 0,
          data.level1Processing || 0,
          data.level1Completed || 0,
          data.level1Closed || 0
        ],
        itemStyle: {
          color: statusColors.success
        }
      },
      {
        name: '二级预警',
        type: 'bar',
        stack: 'total',
        label: {
          show: true
        },
        emphasis: {
          focus: 'series'
        },
        data: [
          data.level2Pending || 0,
          data.level2Processing || 0,
          data.level2Completed || 0,
          data.level2Closed || 0
        ],
        itemStyle: {
          color: statusColors.warning
        }
      },
      {
        name: '三级预警',
        type: 'bar',
        stack: 'total',
        label: {
          show: true
        },
        emphasis: {
          focus: 'series'
        },
        data: [
          data.level3Pending || 0,
          data.level3Processing || 0,
          data.level3Completed || 0,
          data.level3Closed || 0
        ],
        itemStyle: {
          color: statusColors.danger
        }
      }
    ]
  }
  
  warningLevelChart.setOption(option)
}

// 更新月度趋势图表
const updateMonthlyTrendChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['检查任务', '跟踪任务', '评估任务', '预警任务']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.months || []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '检查任务',
        type: 'line',
        stack: 'Total',
        data: data.inspectionCounts || [],
        itemStyle: {
          color: statusColors.primary
        }
      },
      {
        name: '跟踪任务',
        type: 'line',
        stack: 'Total',
        data: data.trackCounts || [],
        itemStyle: {
          color: statusColors.success
        }
      },
      {
        name: '评估任务',
        type: 'line',
        stack: 'Total',
        data: data.assessmentCounts || [],
        itemStyle: {
          color: statusColors.warning
        }
      },
      {
        name: '预警任务',
        type: 'line',
        stack: 'Total',
        data: data.warningCounts || [],
        itemStyle: {
          color: statusColors.danger
        }
      }
    ]
  }
  
  monthlyTrendChart.setOption(option)
}

// 导出报表
const handleExport = () => {
  const params = {
    startDate: filterForm.dateRange[0],
    endDate: filterForm.dateRange[1]
  }
  
  postloanStatisticsApi.exportReport(params).then(res => {
    // 处理文件下载
    const blob = new Blob([res.data], {
      type: 'application/vnd.ms-excel'
    })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `贷后统计报表_${new Date().getTime()}.xlsx`
    link.click()
    URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  }).catch(() => {
    ElMessage.error('导出失败')
  })
}

// 组件挂载时初始化
onMounted(() => {
  handlePeriodChange()
  initCharts()
  fetchData()
})
</script>

<style scoped>
.post-loan-statistics {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 20px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.statistics-card {
  padding: 10px;
  height: 130px;
  margin-bottom: 20px;
}

.statistics-card-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.statistics-card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 20px;
}

.statistics-card-footer {
  font-size: 14px;
  color: #909399;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  font-size: 16px;
  font-weight: bold;
}

.chart-content {
  height: 300px;
}
</style> 